package com.small.site.exception;

import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author  xiaochi
 * @date    2021/11/21 13:38
 * @desc    网关异常过滤器（获取网关调用（转发）的项目发生异常），能把哪些错误的返回拦截掉，并触发网关全局异常处理（JsonExceptionHandler）
 */
@Component
public class GatewayExceptionFilter implements Ordered, GlobalFilter {

    /**
     * 如果需要拦截返回值并处理，这里则需要返回负数
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    /**
     * 异常拦截，拦截响应值不是 200 的数据，并抛给全局异常处理
     */
    @Override
    @SuppressWarnings({"unchecked", "NullableProblems"})
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpResponseDecorator decorated = new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.map(dataBuffer -> {
                        if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
                            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
                        }
                        if (response.getStatusCode() != HttpStatus.OK) {
                            byte[] content = new byte[dataBuffer.readableByteCount()];
                            dataBuffer.read(content);
                            DataBufferUtils.release(dataBuffer); // 释放掉内存
                            String errMsg = new String(content, StandardCharsets.UTF_8);
                            throw new RuntimeException(errMsg);
                        }
                        return dataBuffer;
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decorated).build());
    }
}